package com.dwxt.community.admin.service;

import com.dwxt.community.dao.OfflineActivityMapper;
import com.dwxt.community.entity.IntegralRecord;
import com.dwxt.community.entity.OfflineActivity;
import com.dwxt.community.entity.OfflineActivityExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OfflineActivityServiceAdmin {

    @Autowired
    private OfflineActivityMapper offlineActivityMapper;

    @Autowired
    private IntegralServiceAdmin integralServiceAdmin;

    public PageInfo<OfflineActivity> selectPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        OfflineActivityExample example = new OfflineActivityExample();
        example.setOrderByClause("create_time desc");
        List<OfflineActivity> offlineActivities = offlineActivityMapper.selectByExample(example);
        PageInfo<OfflineActivity> offlineActivityPageInfo = new PageInfo<>(offlineActivities);
        return offlineActivityPageInfo;
    }

    public void createOrUpdateActivity(OfflineActivity offlineActivity) {
        if (offlineActivity.getId() != null) {
            offlineActivityMapper.updateByPrimaryKeySelective(offlineActivity);
            IntegralRecord record = integralServiceAdmin.selectByRelateId(offlineActivity.getId());
            if (record != null) {
                record.setIntegral(offlineActivity.getIntegral());
                record.setCategory(offlineActivity.getName());
                integralServiceAdmin.updateRecord(record);
            }
        } else {
            offlineActivityMapper.insertSelective(offlineActivity);
            integralServiceAdmin.insertActivityRecord(offlineActivity);
        }
    }

    public void delete(Integer id) {
        offlineActivityMapper.deleteByPrimaryKey(id);
        integralServiceAdmin.deleteByRelateId(id);
    }
}
